<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'
import { visitByWeek } from '@/api/dashboard'
export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '200px'
    }
  },
  data() {
    return {
      chart: null,
      dataList: [],
      nameList: []
    }
  },
  mounted() {
    this.visitByWeek()
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    visitByWeek() {
      visitByWeek().then(response => {
        const arr = response.data
        for (let i = 0; i < arr.length; i++) {
          this.dataList.push(arr[i].num)
          this.nameList.push(arr[i].createTime)
          this.$nextTick(() => {
            this.initChart()
          })
        }
      })
    },
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')

      this.chart.setOption({
        title: {
          text: '最近一周访问量',
          subtext: '',
          left: 'left',
          textStyle: {
            color: '#333'
          }
        },
        color: ['#3398DB'],
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: this.nameList,
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '访问量',
            type: 'bar',
            barWidth: '60%',
            data: this.dataList
          }
        ]
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .chart{
    background-color: white;
    box-shadow: 0 2px 14px 0 #f3f3f3;
    border-radius: 8px;
    padding: 10px;
  }
</style>
